﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using fanfu.Business;
using fanfu.Model;
using fanfu.Common;
using System.Data;
using System.Data.SqlClient;
using System.Text;

public partial class AdminUser : BasePage
{
    //所有用户信息
    private DataTable __AdminUser = new DataTable();

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件

        //获取查询条件
        string userName = this.searchUserName.Value.Trim();
        string userAlias = this.searchUserAlias.Value.Trim();
        string startTime = this.searchStartRegistTime.Value.Trim();
        string endTime = this.searchEndRegistTime.Value.Trim();
        string flag = this.searchFlag.SelectedItem.Value;

        #region 备用时间验证
        //DateTime startRegistTime = new DateTime();
        //DateTime endRegistTime = new DateTime();
        //if (startTime != "" && endTime != "")
        //{
        //    if (DateTime.TryParse(startTime, out startRegistTime) &&
        //        DateTime.TryParse(endTime, out endRegistTime))
        //    {
        //        //可以转换成日期型
        //    }
        //    else
        //    {
        //        this.searchStartRegistTime.Value = "";
        //        this.searchEndRegistTime.Value = "";
        //        RunJavascript("PopupMsg('error','错误,注册时间格式不正确！');", true);
        //        return;
        //    }
        //}
        #endregion
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM AdminUser WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (userName != "")
        {
            sqlString += "AND UserName like @UserName ";
            paraList.Add(new SqlParameter("@UserName", "%"+userName+"%"));
        }
        if (userAlias != "")
        {
            sqlString += "AND UserAlias like @UserAlias ";
            paraList.Add(new SqlParameter("@UserAlias", "%"+userAlias+"%"));
        }
        if (startTime != "")
        {
            sqlString += "AND RegistTime>=@StartRegistTime ";
            paraList.Add(new SqlParameter("@StartRegistTime", Convert.ToDateTime(startTime)));
        }
        if (endTime != "")
        {
            sqlString += "AND RegistTime<@EndRegistTime ";
            paraList.Add(new SqlParameter("@EndRegistTime", Convert.ToDateTime(endTime).AddDays(1)));
        }
        if (flag != "0")
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        sqlString += "ORDER BY RegistTime DESC";
        #endregion

        //给数据列表赋值
        __AdminUser = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __AdminUser.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__AdminUser.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchUserName.Value = "";
        this.searchUserAlias.Value="";
        this.searchStartRegistTime.Value="";
        this.searchEndRegistTime.Value="";
        this.searchFlag.SelectedIndex = 0;

        //给数据列表赋值
        __AdminUser = new AdminUserRule().GetAllUserInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __AdminUser.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__AdminUser.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";            //清除编辑的ID
        this.deleteID.Value = "";          //清除删除的ID
        this.txtUserName.Disabled = false; //用户名可编辑
        this.editState.Value = "false";    //取消编辑状态
        RunJavascript("AddNew();", true); //JS清空控件值
        Session.Remove("OldPassword");     //清除OldPassword
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定用户状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(AdminUserFlag));
            //绑定列表并转到第一页
            BindAllData(this.rptDataList, 1);
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 编辑事件
    protected void lbtnEdit_Click(object sender, EventArgs e)
    {   
        //设置编辑状态,选项卡跳转
        this.editState.Value = "true";
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            AdminUserModel adminUser = new AdminUserRule().GetUserInfoByID(editID);
            //留存一份修改前的原密码到Session
            Session["OldPassword"] = adminUser.UserPassword;
            //绑定值到页面控件
            this.txtUserName.Value = adminUser.UserName;
            this.txtUserPwd.Attributes.Add("value ", adminUser.UserPassword);
            this.txtAffirmUserPwd.Attributes.Add("value ", adminUser.UserPassword);
            this.txtUserAlias.Value = adminUser.UserAlias;
            if (adminUser.Flag.ToString() == "1")
            {
                this.Flag_1.Checked = true;
                this.Flag_2.Checked = false;
                this.Flag_3.Checked = false;
            }
            if (adminUser.Flag.ToString() == "2")
            {
                this.Flag_2.Checked = true;
                this.Flag_1.Checked = false;
                this.Flag_3.Checked = false;
            }
            if (adminUser.Flag.ToString() == "3")
            {
                this.Flag_3.Checked = true;
                this.Flag_1.Checked = false;
                this.Flag_2.Checked = false;
            }
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new AdminUserRule().DeleteUser(item);
            }
            if (result == values.Length)
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            else
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string userName = this.txtUserName.Value.Trim();
        string userPwd = this.txtUserPwd.Value.Trim();
        string userAlias = this.txtUserAlias.Value.Trim();
        byte flag = (byte)AdminUserFlag.normal;
        if (this.Flag_2.Checked)
            flag = (byte)AdminUserFlag.locked;
        if (this.Flag_3.Checked)
            flag = (byte)AdminUserFlag.delete;

        //获取当前用户信息用于判断是不是修改的当前登录用户
        string currentUserName = CookieHelper.GetCookie("userName");
        AdminUserModel currentUser = new AdminUserRule().GetUserInfoByName(currentUserName);
       
        //判断用户名是否已存在
        string editID = this.editID.Value;
        AdminUserModel nameIsExist = new AdminUserRule().GetUserInfoByName(userName);
        if (nameIsExist.ID != 0 && nameIsExist.ID.ToString() != editID)
        {
            RunJavascript("PopupMsg('error','用户" + userName + "已存在,请更换用户名！');", true);
            RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            return;
        }

        //是否是修改状态
        if (this.editState.Value == "true")
        {
            //是否修改过密码,try主要是预防Session["OldPassword"]丢失的情况
            try
            {
                if (userPwd != Session["OldPassword"].ToString())
                    userPwd = MD5.MD5ToHexString(userPwd);
            }
            catch (Exception ex)
            {
                return;
            }

            //更新用户
            string sqlString = "UPDATE AdminUser SET UserName=@UserName, UserPassword=@UserPassword, UserAlias=@UserAlias, Flag=@Flag WHERE ID=@ID";
            List<SqlParameter> paraList = new List<SqlParameter>();
            paraList.Add(new SqlParameter("@UserName", userName));
            paraList.Add(new SqlParameter("@UserPassword",userPwd));
            paraList.Add(new SqlParameter("@UserAlias", userAlias));
            paraList.Add(new SqlParameter("@Flag", flag));
            paraList.Add(new SqlParameter("@ID", editID));
            int result = SqlHelper.ExecuteCommand(sqlString, paraList.ToArray());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,更新成功！');", true);

                #region 是否是修改的当前用户,如果是则修改cookie并重新登录
                //是否是修改的当前用户,如果是则修改cookie并重新登录
                if (currentUser.ID.ToString() == editID)
                {
                    string isRememberPwd = CookieHelper.GetCookie("rememberPwd");
                    if (isRememberPwd == "true")
                    {
                        CookieHelper.SaveCookie("userName", userName, 14);
                        CookieHelper.SaveCookie("userPwd", userPwd, 14);
                    }
                    else
                    {
                        CookieHelper.ClearCookie("userName");
                    }    
                    CookieHelper.ClearCookie("loginState");
                    CookieHelper.ClearCookie("userAlias");
                    Response.Redirect("Login.aspx");
                }
                #endregion
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,更新失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }
        else
        {
            //新增用户
            userPwd = MD5.MD5ToHexString(userPwd);
            AdminUserModel adminUser = new AdminUserModel();
            adminUser.UserName = userName;
            adminUser.UserPassword = userPwd;
            adminUser.UserAlias = userAlias;
            adminUser.RegistTime = DateTime.Now;
            adminUser.LastLoginTime = Convert.ToDateTime("1753-1-1");
            adminUser.LoginCount = 0;
            adminUser.LastLoginIP = "未登录过";
            adminUser.Flag = flag;
            int result = SqlHelper.ExecuteCommand(AdminUserModel.GetInsertSQL(), adminUser.ToSqlParameters());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,新建成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,新建失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}